package pattern.virtualproxy;

import java.net.URL;

import javax.swing.ImageIcon;

public class ImageProxy implements Icon
{
	ImageIcon imageIcon;
	URL url;
	Thread retrievalThread;
	boolean retrieving = false;
	
	public ImageProxy(URL url)
	{
		this.url = url;
	}

	@Override
	public int getIconWidth()
	{
		if(imageIcon!=null)
		{
			return imageIcon.getIconWidth();
		}else
		{
			return 600;
		}
	}

	@Override
	public int getIconHeight()
	{
		return 0;
	}

	@Override
	public void paintIcon()
	{
		if(imageIcon!=null)
		{
			System.out.println("show");
		}else
		{
			System.out.println("loading...");
			if(!retrieving)
			{
				retrieving = true;
				retrievalThread = new Thread(new Runnable()
				{
					
					@Override
					public void run()
					{
						imageIcon = new ImageIcon(url, "image");
						System.out.println("image repaint");
					}
				});
			}
			retrievalThread.start();
		}
	}
	
}
